<template>
  <div id="app" style="font-size: 26px; font-weght: bold; margin: 30px 0">
    <header class="header">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item
          :label="item.title + ':'"
          v-for="(item, index) in topInputList"
          :key="index"
        >
          <el-input
            v-model="item.text"
            :placeholder="item.title"
            class="top-input"
          ></el-input>
        </el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="search"
          >搜索</el-button
        >
      </el-form>
      <!-- <el-input
        placeholder=""
        v-for="(item, index) in topInputList"
        :key="index"
        v-model="item.text"
        :placeholder="item.title"
        class="top-input"
      ></el-input>
      <el-button type="primary" icon="el-icon-search" @click="search"
        >搜索</el-button
      > -->
    </header>

    <el-table
      v-loading="loading"
      :data="tableData"
      max-height="600"
      border
      fit
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="ID" width="70" prop="id"> </el-table-column>

      <!-- <el-table-column
        show-overflow-tooltip
        prop="id"
        label="ID"
        width="80">
      </el-table-column> -->
      <el-table-column
        show-overflow-tooltip
        prop="nickname"
        label="用户名"
        width=""
      >
      </el-table-column>
      <el-table-column label="头像" show-overflow-tooltip width="100">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.aavatar[0]"
            :preview-src-list="scope.row.aavatar"
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="grade"
        label="等级"
        width="80"
      >
      </el-table-column>
      <el-table-column show-overflow-tooltip label="身份" width="">
        <template slot-scope="scope">
          {{ scope.row.user_authority_text }}
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="mobile"
        label="手机号码"
        width=""
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="paiming"
        label="排名"
        width="80"
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="balance"
        label="余额"
        width="120"
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="fx_renshus"
        label="分享总人数"
        width="110"
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="fx_renshu"
        label="本月分享人数"
        width="120"
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="pid_mobile"
        label="邀请人"
        width="120"
      >
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="cctime"
        label="创建时间"
        width=""
      >
      </el-table-column>
      <el-table-column label="操作" show-overflow-tooltip width="100">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50, 60]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <el-dialog
      title="编辑用户"
      :visible.sync="outerVisible"
      :before-close="handleClosediaLoding"
    >
      <el-form
        label-position="right"
        label-width="80px"
        :model="formLabelAlign"
      >
        <div class="oneLine">
          <el-form-item label="用户名">
            <el-input v-model="formLabelAlign.name"></el-input>
          </el-form-item>
          <el-form-item label="等级">
            <el-select v-model="formLabelAlign.grade" placeholder="等级">
              <el-option label="0" value="0"></el-option>
              <el-option label="1" value="1"></el-option>
              <el-option label="2" value="2"></el-option>
              <el-option label="3" value="3"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="oneLine">
          <el-form-item label="头像">
            <div class="unlodBox">
              <el-upload
                class="upload-demo"
                action
                :http-request="uploadFile"
                ref="upload"
                :limit="fileLimit"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :headers="headers"
              >
                <el-button size="mini" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5M
                </div>
              </el-upload>
              <el-image
                style="width: 100px; height: 100px"
                :src="formLabelAlign.atavar"
                fit="cover"
              ></el-image>
            </div>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeVisible">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { uploadFilec, getUserList, setUserData } from "../../../utils/api";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      token: sessionStorage.getItem("token"),
      topInputList: [
        { title: "手机号", text: "" },
        { title: "用户昵称", text: "" },
        { title: "邀请人手机号", text: "" },
        // { title: 'ID', text: '' },
      ],
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      total: 0,
      limit: 10,
      loading: true,
      imgHeader: this.Global.imgHeader,

      outerVisible: false,
      formLabelAlign: {
        name: "",
        grade: "",
        atavar: "",
        avatar: "",
        id: "",
      },
      fileList: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 1,
      headers: { "Content-Type": "multipart/form-data" },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    save() {
      let data = {
        avatar: this.formLabelAlign.avatar,
        nickname: this.formLabelAlign.name,
        grade: this.formLabelAlign.grade,
      };
      setUserData(
        this.token,
        this.formLabelAlign.id,
        JSON.stringify(data)
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.outerVisible = false;
          this.getUserList(
            this.token,
            this.currentPage,
            this.limit,
            this.topInputList[0].text,
            "",
            this.topInputList[1].text,
            this.topInputList[2].text
          );
        } else {
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
            let timer = setTimeout(() => {
              this.$message.error("错误，请刷新");
            }, 5000);
          }
          this.$message.error(res.data.msg);
        }
      });
    },
    closeVisible() {
      this.outerVisible = false;
      this.formLabelAlign.name = "";
      this.formLabelAlign.grade = "";
      this.formLabelAlign.atavar = "";
      this.formLabelAlign.avatar = "";
      this.formLabelAlign.id = "";
      // this.outerVisible = false
    },
    handleClosediaLoding() {
      this.outerVisible = false;
      this.formLabelAlign.name = "";
      this.formLabelAlign.grade = "";
      this.formLabelAlign.atavar = "";
      this.formLabelAlign.avatar = "";
      this.formLabelAlign.id = "";
    },
    // 选中的用户
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    handleSizeChange(val) {
      this.limit = val;
      console.log(`每页 ${val} 条`);
      this.getUserList(
        this.token,
        this.currentPage,
        this.limit,
        this.topInputList[0].text,
        "",
        this.topInputList[1].text,
        this.topInputList[2].text
      );
    },
    // 第几页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUserList(
        this.token,
        this.currentPage,
        this.limit,
        this.topInputList[0].text,
        "",
        this.topInputList[1].text,
        this.topInputList[2].text
      );
    },
    // 获取用户信息
    getUserList(token, page, limit, mobile, id, nickname, pid_mobile) {
      this.loading = true;
      getUserList(token, page, limit, mobile, id, nickname, pid_mobile).then(
        (res) => {
          console.log(res.data);
          if (res.data.status) {
            this.tableData = res.data.data.data;
            this.total = res.data.data.count;
            this.tableData.forEach((item) => {
              item.cctime = this.parseTime(item.ctime);
              item.aavatar = [];
              item.aavatar.push(this.imgHeader + item.avatar);
              // `user_authority` tinyint(255) DEFAULT '10' COMMENT '3=维修工 4=查勘员 5=送水工  6 商户 10=默认用户 ',
              if (item.user_authority == 10) {
                item.user_authority_text = "普通用户";
              }
              if (item.user_authority == 3) {
                item.user_authority_text = "维修工";
              }
              if (item.user_authority == 4) {
                item.user_authority_text = "查勘员";
              }
              if (item.user_authority == 5) {
                item.user_authority_text = "送水工";
              }
              if (item.user_authority == 6) {
                item.user_authority_text = "商户";
              }
            });
            let timer = setTimeout(() => {
              this.loading = false;
              clearTimeout(timer);
            }, 400);
          } else {
            if (res.data.msg == "token失效,请重新进行登录") {
              this.$router.push("/login");
            }
            let timer = setTimeout(() => {
              this.loading = false;
              this.$message.error("错误，请刷新");
            }, 5000);
          }
        }
      );
    },

    search() {
      // console.log(this.topInputList[0].text) id
      // console.log(this.topInputList[1].text) 手机号
      // console.log(this.topInputList[2].text) 用户名称
      this.currentPage = 1;
      this.getUserList(
        this.token,
        this.currentPage,
        this.limit,
        this.topInputList[0].text,
        "",
        this.topInputList[1].text,
        this.topInputList[2].text
      );
    },

    handleEdit(index, row) {
      console.log(index, row);
      this.outerVisible = true;
      this.formLabelAlign.name = row.nickname;
      this.formLabelAlign.grade = row.grade;
      this.formLabelAlign.atavar = row.aavatar[0];
      this.formLabelAlign.id = row.id;
      this.formLabelAlign.avatar = row.avatar;
    },
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    handleRemove() {},
    //这是我自定义的移除事件
    handleClose(i) {
      console.log(i);
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //序号排序
    indexMethod(index) {
      if (this.token < this.limit) {
        return this.total - index;
      } else {
        return this.total - (this.currentPage - 1) * this.limit - index;
      }
    },
    //上传文件的事件
    uploadFile(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      uploadFilec(item.file).then((res) => {
        if (res.data.status != false || res.data.id != null) {
          console.log(res);
          res.data.data.saveurl; //半截
          res.data.data.weburl; //全拼
          this.formLabelAlign.atavar = res.data.data.weburl;
          this.formLabelAlign.avatar = res.data.data.saveurl;
          this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
          let i = this.fileList.indexOf(item.file);
          this.handleSuccess();
        }
      });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClose();
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getUserList(
      this.token,
      this.currentPage,
      this.limit,
      this.topInputList[0].text,
      "",
      this.topInputList[1].text,
      this.topInputList[2].text
    );
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped >
#app {
  width: 100%;
}

/deep/.header {
  background: white !important;
  box-shadow: 0 5px 10px #ddd;
  min-height: 40px;
  display: flex;
  padding: 10px;
}

.top-input {
  width: 150px;
  margin-right: 20px;
}

/deep/.el-table th.el-table__cell > .cell {
  text-align: center;
}

/deep/.el-table--border .el-table__cell:first-child .cell {
  text-align: center;
}

/deep/.el-table .cell.el-tooltip {
  text-align: center;
}

.el-table {
  margin: 20px 0;
}

/deep/.el-checkbox:last-of-type {
  margin-left: 0;
}

.oneLine {
  display: flex;
  justify-content: space-between;
}

/deep/.el-dialog__wrapper .el-dialog {
  width: 35%;
}

/deep/.upload-demo .el-upload--text {
  border: none;
  width: auto;
  height: auto;
}

.upload-demo {
  line-height: normal;
  margin-bottom: 20px;
}
</style>
